package com.atguigu.service.impl;

import com.atguigu.dao.UserDao;
import com.atguigu.domain.Role;
import com.atguigu.domain.UserInfo;
import com.atguigu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);
//        User user = new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthorities());
        User user = new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getStatus() == 0 ? false : true, true, true, true, getAuthorities(userInfo.getRoles()));
        return user;
    }

    List<SimpleGrantedAuthority> getAuthorities(List<Role> roles){
        List<SimpleGrantedAuthority> list = new ArrayList<>();
//        list.add(new SimpleGrantedAuthority("ROLE_USER"));
        for (int i = 0; i < roles.size() ; i++) {
            list.add(new SimpleGrantedAuthority("ROLE_"+roles.get(i).getRoleName()));
        }

        return list;
    }

    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    @Override
    public void sava(UserInfo userInfo) {
        userDao.sava(userInfo);
    }

    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }


    @Override
    public List<Role> findOtherRoles(String id) {
        return userDao.findOtherRoles(id);
    }


    @Override
    public void saveuserAndRole(String userId, String[] roleIds) {
        for (String roleId:roleIds) {
            userDao.saveuserAndRole(userId, roleId);
        }
    }

}
